package net.jlibrary.common.project.util;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpClientUtils {
	private static final String UTF8 = "UTF-8";
	private static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";

	public static final String POST_REQUEST = "POST";
	private static final String CONTENT_TYPE_JSON = "application/json";

	public static String tokenString = "";

	/**
	 * POST 模式提交
	 * 
	 * @param url   请求URL 地址
	 * @param param 请求参数json
	 * @return
	 */
	public static String doPostFormToJson(String url, String token, String param) {
		String result = "";
		HttpResponse response = null;
		HttpPost httpost = new HttpPost(url);
		// httpost.setHeader("Authorization", "Bearer " + token);
		httpost.addHeader("User-Agent",
				"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
		if (!StringUtils.isBlank(token)) {
			httpost.addHeader("token", token);
		}
		CloseableHttpClient httpclient = HttpClients.custom().build();
		try {
			// 解决中文乱码问题
			// StringEntity entity = new StringEntity(param);
			StringEntity entity = new StringEntity(param, "UTF-8");
			// entity.setContentEncoding(UTF8);
			entity.setContentType(CONTENT_TYPE_JSON);
			httpost.setEntity(entity);

			response = httpclient.execute(httpost);
			result = EntityUtils.toString(response.getEntity());

		} catch (Exception e) {
			System.out.println("调用接口发生异常，" + e);
		} finally {
			try {
				EntityUtils.consume(response.getEntity());
			} catch (Exception e) {
				System.out.println("调用接口组装result异常，" + e);
			}
			httpost.abort();
		}
		return result;
	}

}
